package org.devocean.groupbuying.dao.impl;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.devocean.groupbuying.dao.VoucherDAO;
import org.devocean.groupbuying.domain.SerialKey;
import org.devocean.groupbuying.domain.Voucher;
import org.springframework.stereotype.Repository;

@Repository
public class VoucherDAOImpl implements VoucherDAO {

	@PersistenceContext
	private EntityManager em;
	
	
	public void linkToSerialKey(Voucher voucher) {
		
		for (SerialKey serialKey : voucher.getSerialKeys()) {
			serialKey.setVoucher(voucher);
		}

	}

	public List<Voucher> findAllVouchers() {

		return em.createQuery("select v from Voucher v", Voucher.class)
				.getResultList();
	}

	public long countVoucher() {
		return em.createQuery("select count(vu) from Voucher vu", long.class)
				.getSingleResult();
	}

	public Voucher findVoucherById(Integer id) {
		return em.find(Voucher.class, id);
	}

	public void deleteVoucher(int id) {
		final Voucher voucher = em.find(Voucher.class, id);
		if (voucher != null) {
			em.remove(voucher);
		}

	}

	public Voucher saveVoucher(Voucher voucher) {
		linkToSerialKey(voucher);
		em.persist(voucher);
		return voucher;
	}

	public Voucher updateVoucher(Voucher voucher) {
		linkToSerialKey(voucher);
		em.merge(voucher);
		return voucher;
	}

	public SerialKey findValidSerialKey(Integer VoucherID) {
		final Query query = em
				.createQuery(
						"select s from SerialKey s where s.voucher.voucherID=:vid and s.valid=1 ",
						SerialKey.class);
		query.setParameter("vid", VoucherID);

		return (SerialKey) query.getResultList().get(0);
	}

	public Voucher findVoucherByDiscountID(Integer DiscountID) {
		 List<Voucher> vouchers = em.createQuery("select v from Voucher v JOIN FETCH v.discount d where d.discountID = :DiscountID",
				 Voucher.class).setParameter("DiscountID", DiscountID)
				 .getResultList();
		 if(vouchers.size() > 0)
			 return vouchers.get(0);
		 else
			 return null;
	}

	public void deleteSerial(Integer id) {
		SerialKey serialKey = em.find(SerialKey.class, id);
		if(serialKey != null)
			em.remove(serialKey);
		
	}

}
